package net.xuele.learn.interrupt;

import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class Shutdown {
    public static void main(String[] args) throws Exception {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "CountThread");
        countThread.start();
        // 睡眠1秒，main线程对CountThread进行中断，使CountThread能够感知中断而结束
        TimeUnit.SECONDS.sleep(1); //Thread.sleep(1000);
        countThread.interrupt();
        System.out.println("是否停止1：" + countThread.isInterrupted());
        Runner two = new Runner();
        countThread = new Thread(two, "CountThread");
        countThread.start();
        // 睡眠1秒，main线程对Runner two进行取消，使CountThread能够感知on为false而结束
        TimeUnit.SECONDS.sleep(1);
        two.cancel();
        System.out.println("是否停止2：" + countThread.isInterrupted());
    }

    private static class Runner implements Runnable {
        private long i;

        private volatile boolean on = true;

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println("Count i = " + i);
        }

        public void cancel() {
            on = false;
        }
    }

    @Test
    public void test1() {
        Runnable tr = new TestRunnable();
        Thread th1 = new Thread(tr);
        th1.start(); // 开始执行分线程
        while (true) {
//
            th1.interrupt(); // 中断这个分线程
        }
//        th1.interrupt();
    }


    static class TestRunnable implements Runnable {
        public void run() {
            try {
                Thread.sleep(1000000); // 这个线程将被阻塞1000秒
            } catch (InterruptedException e) {
                e.printStackTrace();
                System.out.println("是否停止：" + Thread.currentThread().isInterrupted());
            }
        }
    }
}
